var express=require('express'),
    app=express(),
    fs=require('fs'),
    bodyParser=require('body-parser'),
    dataOne=require('./data/index1.json'),
    dataTwo=require('./data/index2.json'),
    dataThree=require('./data/index3.json'),
    banner=require('./data/banner.json'),
    data={
        dataOne:dataOne,
        dataTwo:dataTwo,
        dataThree:dataThree,
        banner:banner,
    };
    app.get('/',function(req,res){
        res.header('Access-Control-Allow-Origin', '*');
        var path=req.query.q;
        res.send(data[path]);
    });
    app.use(bodyParser.urlencoded({
        extended:false
    }));
    app.post('/changeFs',function(req,res){
        res.header('Access-Control-Allow-Origin','*');
        var command=req.body.command,
            argument=req.body.argument;
        if(command=='add'&&argument){
            fs.appendFile('./data/data.txt',argument,function(err){
                if(!err){
                    res.send('add_ok');
                }
            })
        }
        if(command=='remove'){
            fs.unlink('./data/data.txt', function () {
                fs.open('./data/data.txt','w+',function(err,fd){
                    if(!err){
                        res.send('remove_ok');
                        fs.close(fd);
                    }
                })
            })
        }
    })
    app.get('/getFs',function(req,res){
        res.header('Access-Control-Allow-Origin','*');
        fs.readFile('./data/data.txt','utf-8',function(err,data){
            if(!err){
                res.send(data);
            }
        })
    })
    app.listen('4500',function(err){
        if(!err){
            console.log('server running at localhost:4500');
        }
    });